package com.example.newhabitclock.HabitAlarm

import android.annotation.SuppressLint
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import com.example.newhabitclock.HabitRoomPackage.Habit
import java.util.Calendar

object AlarmHelper {
    private val dayMap = mapOf(
        "一" to Calendar.MONDAY,
        "二" to Calendar.TUESDAY,
        "三" to Calendar.WEDNESDAY,
        "四" to Calendar.THURSDAY,
        "五" to Calendar.FRIDAY,
        "六" to Calendar.SATURDAY,
        "七" to Calendar.SUNDAY
    )

    /**
     * 为所有习惯设置闹钟
     */
    @SuppressLint("ScheduleExactAlarm")
    fun setAlarmsForHabits(context: Context, habits: List<Habit>) {
        val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager

        habits.filter { it.isCallIn }.forEach { habit ->
            val timeParts = habit.time.split(":")
            if (timeParts.size != 2) return@forEach // 格式错误，跳过
            val hour = timeParts[0].toIntOrNull() ?: return@forEach
            val minute = timeParts[1].toIntOrNull() ?: return@forEach

            habit.repeatDays.forEach { repeatDay ->
                val dayOfWeek = dayMap[repeatDay] ?: return@forEach

                // 计算下一次触发时间
                val calendar = Calendar.getInstance().apply {
                    set(Calendar.HOUR_OF_DAY, hour)
                    set(Calendar.MINUTE, minute)
                    set(Calendar.SECOND, 0)
                    set(Calendar.MILLISECOND, 0)
                    set(Calendar.DAY_OF_WEEK, dayOfWeek)
                    // 如果时间已过，推迟到下周
                    if (timeInMillis < System.currentTimeMillis()) {
                        add(Calendar.WEEK_OF_YEAR, 1)
                    }
                }

                // 创建PendingIntent
                val intent = Intent(context, HabitAlarmReceiver::class.java).apply {
                    putExtra("habit_id", habit.id)
                    putExtra("habit_name", habit.name)
                }
                val requestCode = generateRequestCode(habit.id, dayOfWeek)
                val pendingIntent = PendingIntent.getBroadcast(
                    context,
                    requestCode,
                    intent,
                    PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
                )

                // 设置精确闹钟
                alarmManager.setExactAndAllowWhileIdle(
                    AlarmManager.RTC_WAKEUP,
                    calendar.timeInMillis,
                    pendingIntent
                )
            }
        }
    }

    /**
     * 生成唯一的requestCode
     */
    private fun generateRequestCode(habitId: Int, dayOfWeek: Int): Int {
        return habitId * 10 + dayOfWeek
    }
}